<?php

namespace app\user\controller;

use app\common\model\Users;
use think\Request;

class User extends Base
{

	public function index(Request $request)
	{
		if ( $this->user['admin'] != 3 ) exit('<h1>没有权限访问此页面</h1>');
		if ( $request->isAjax() ){

			$page = input('param.page/d', 1);
			$limit = input('param.limit/d', 20);
			$data = array(
				'data'      => Users::field('password', true)->where('uid', session('user.id'))->order(['id'=>'desc'])->page($page)->limit($limit)->select(),
				'count'     => Users::count('id'),
				'code'      => 0,
				'msg'       => '',
			);
			return json($data);
		}
		return view();
	}


	// 添加
	public function create(Request $request)
	{
		if ( $this->user['admin'] != 3 ) exit('<h1>没有权限访问此页面</h1>');
		if ( $request->isPost() ){
			$post = trimAll($request->post());
			$post['uid']  = session('user.id');
			$post['status'] = isset($post['status']) ? $post['status'] : 2;
			$post['admin'] = 2;
			$post['create_time'] = time();

			// 新用户试用期时长
			$newuserendtime = (int)fission('newuserendtime');
			if ( $newuserendtime ) $newuserendtime = 3;

			$post['end_time'] = time() + 60*60*24*$newuserendtime;


			$post['password'] = sha1_password($post['password']);

			if ( Users::create($post) ){
				createLog('添加用户成功：' . $post['username']);
				success('保存成功');
			}else{
				createLog('添加用户失败');
				error('保存失败');
			}
		}
		return view();
	}

	public function edit(Request $request, $id)
	{
		if ( $this->user['admin'] != 3 ) exit('<h1>没有权限访问此页面</h1>');
		if ( $request->isPost() ){
			$post = trimAll($request->post());
			$post['status'] = isset($post['status']) ? $post['status'] : 2;

			if ( $post['password'] ){
				$post['password'] = sha1_password($post['password']);
			} else {
				unset($post['password']);
			}

			if ( Users::where('id', $id)->update($post) ){
				createLog('编辑用户成功' . $post['username']);
				success('保存成功');
			} else {
				createLog('编辑用户失败' . $post['username']);
				error('保存失败');
			}
		}
		$data = Users::get($id);
		$this->assign('data', $data);
		return view();
	}

	// 续费
	public function xufei(Request $request)
	{
		if ($request->isPost()){
			$id = $request->post('id');
			$tian = (int)$request->post('tian');
			if ( !$tian ) error('请输入正确的数字（不能为0）');

			// 获取用户信息
			$user = Users::field('password', true)->get($id);

			// 如果用户已过期，从当前时间开始计算
			if ( (int)$user['end_time'] < time() ){
				$user->end_time = time() + 60*60*24*$tian;
				$user->save();
			} else {
				$user->end_time = $user->end_time + 60*60*24*$tian;
				$user->save();
			}
			success('充值成功');
		}
	}


}
